<?php

namespace app\adminapi\controller;

use app\model\UsersModel;
use app\service\MessageService;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\Redis;
use Webman\Http\Request;

class User extends BaseAdminApi
{
    protected $dataModel = UsersModel::class;
    protected array $allowSearch = ['nickname', 'username', 'email', 'phone', 'status'];

    /**
     * 不需要登录的方法
     * @var array
     */
    protected array $noNeedLogin = ['wechatLogin'];

    /**
     * 保存用户
     */
    public function saveUser(Request $request)
    {
        $raw = $request->post();
        try {
            $params = v::input($raw, [
                'id' => v::optional(v::intVal()->min(1))->setName('用户ID'),
                'nickname' => v::stringType()->notEmpty()->length(1, 50)->setName('昵称'),
                'email' => v::optional(v::email()->length(1, 100))->setName('邮箱'),
                'gender' => v::optional(v::intVal()->in([0,1,2]))->setName('性别'),
                'birthday' => v::optional(v::date())->setName('生日'),
                'status' => v::intVal()->in([0,1])->setName('状态'),
                'username' => v::optional(v::stringType()->length(4, 50))->setName('用户名'),
                'password' => v::optional(v::stringType()->length(6, 50)->regex('/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/'))->setName('密码'),
            ]);

            // 如果提供了用户名或密码，则两者都必须提供
            $hasUsername = isset($params['username']) && $params['username'] !== '';
            $hasPassword = isset($params['password']) && $params['password'] !== '';
            if ($hasUsername xor $hasPassword) {
                return $this->fail('用户名与密码需同时提供');
            }
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑用户
                $user = UsersModel::find($params['id']);
                if (!$user) {
                    return $this->fail('用户不存在');
                }

                // 检查用户名是否重复（排除自己）
                if (!empty($params['username'])) {
                    $existUser = UsersModel::where('username', $params['username'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existUser) {
                        return $this->fail('用户名已存在');
                    }
                }



                // 检查邮箱是否重复（排除自己）
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existEmail) {
                        return $this->fail('邮箱已存在');
                    }
                }

                $updateData = [
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status']
                ];

                // 如果提供了用户名，则更新
                if (!empty($params['username'])) {
                    $updateData['username'] = $params['username'];
                    $updateData['login_type'] = 'username';
                }

                // 如果提供了新密码，则更新密码
                if (!empty($params['password'])) {
                    $updateData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }

                $user->update($updateData);

                return $this->success('用户更新成功');
            } else {
                // 新增用户
                $userData = [
                    'id' => randomString(),
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status'],
                    'login_type' => 'username'
                ];

                // 如果提供了用户名和密码
                if (!empty($params['username']) && !empty($params['password'])) {
                    // 检查用户名是否重复
                    $existUser = UsersModel::where('username', $params['username'])->first();
                    if ($existUser) {
                        return $this->fail('用户名已存在');
                    }
                    
                    $userData['username'] = $params['username'];
                    $userData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }



                // 检查邮箱是否重复
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])->first();
                    if ($existEmail) {
                        return $this->fail('邮箱已存在');
                    }
                }

                UsersModel::create($userData);

                return $this->success('用户创建成功');
            }
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 删除用户
     */
    public function deleteUser(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::stringType()->notEmpty()->setName('用户ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return $this->fail('用户不存在');
            }

            // 删除用户
            $user->delete();

            return $this->success('用户删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 禁用/启用用户
     */
    public function toggleUserStatus(Request $request)
    {
        try {
            $params = v::input($request->post(), [
                'id' => v::stringType()->notEmpty()->setName('用户ID'),
                'status' => v::intVal()->in([0,1])->setName('状态'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return $this->fail('用户不存在');
            }

            $user->update(['status' => $params['status']]);

            if($params['status'] == 1){
                $statusText = '启用';
                $msgText = '你的账号封禁时长已结束，现已恢复正常使用。后续请遵守平台规则，共同维护良好环境';

            }else{
                $statusText = '禁用';
                $msgText = '因你在平台发布的内容违反《社区管理规定》 具体违规类型，如：恶意营销 / 辱骂他人等，账号已被临时封禁。';
            }

            MessageService::sendMessage("system",$params['id'], $msgText,9);

            return $this->success('用户' . $statusText . '成功');
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(Request $request)
    {
        $token = $request->header('authorization');
        
        if (!$token) {
            return $this->fail('请先登录', 401);
        }

        $userId = Redis::get($token);
        
        if (!$userId) {
            return $this->fail('登录已过期', 401);
        }

        $user = UsersModel::find($userId);
        
        if (!$user) {
            return $this->fail('用户不存在', 401);
        }

        return $this->success($user);
    }
}